<?php

namespace app\admin\controller\admin;

use app\common\controller\AdminController;
use app\common\services\annotation\ControllerAnnotation;
use app\common\services\annotation\NodeAnnotation;
use app\common\services\tool\CommonTool;
use Juhelib\excel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use support\Log;
use support\Request;
use support\Response;
use think\Exception;
use think\facade\Db;
use function Symfony\Component\Translation\t;

/**
 * @ControllerAnnotation(title="activity")
 * @package app\admin\controller
 */
class ActivityController extends AdminController
{

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\Activity();
    }

    /**
     * @NodeAnnotation(title="列表")
     */
    public function index(Request $request): Response
    {
        if (!$request->isAjax()) return $this->fetch();
        if ($request->input('selectFields')) {
            return $this->selectList();
        }
        list($page, $limit, $where) = $this->buildTableParams();
        $count = $this->model->where($where)->count();
        $list  = $this->model->where($where)->order($this->order)->page($page, $limit)->select()->toArray();
        foreach ($list as &$value) {
            // 加密code
            $data['code'] = urlencode(base64_encode($value['id']));
            // 销售数量
            $data['order_count'] = Db::name('order')->where(['activity_id' => $value['id'], 'order_status' => 2])->count();
            // 销售金额
            $data['order_total_price'] = Db::name('order')->where(['activity_id' => $value['id'], 'order_status' => 2])->sum('total_price');
            // 推荐奖励
            $data['payment_disburse_amount'] = Db::name('payment_disburse')
                ->where(['status' => 1, 'activity_id' => $value['id']])
                ->sum('amount');
            // 翻牌奖励
            $data['activity_prize_count'] = Db::name('payment_activity_prize')
                ->where(['activity_id' => $value['id']])
                ->count();
            // 平台盲盒
            $data['platform_box_prize_count'] = Db::name('payment_platform_box')
                ->where(['activity_id' => $value['id']])
                ->count();
            // 统计员工直推数量
            $clerk_user_ids = Db::name('activity_user_role')->where(['activity_id' => $value['id'], 'role' => 2])->column('user_id');
            $data['clerk_recom_num'] = Db::name('order')->where([['activity_id', '=', $value['id']] ,['recom_user_id', 'in', $clerk_user_ids]])->count();
            // 统计非员工直推数量
            $data['user_recom_num'] = Db::name('order')->where([['activity_id', '=', $value['id']] ,['recom_user_id', 'not in', $clerk_user_ids]])->count();
            // 新客统计
            $data['new_customer_num'] = Db::name('order')->where(['activity_id' => $value['id'], 'customer_type' => '新客'])->count();
            // 老客统计
            $data['old_customer_num'] = Db::name('order')->where(['activity_id' => $value['id'], 'customer_type' => '老客'])->count();
            // 数据合并
            $value = array_merge($value, $data);
        }
        $data  = [
            'code'  => 0,
            'msg'   => '',
            'count' => $count,
            'data'  => $list,
        ];
        return json($data);
    }

    /**
     * @NodeAnnotation(title="添加")
     */
    public function add(Request $request): Response
    {
        if ($request->isAjax()) {
            $post = $request->post();
            try {
                // 收款账户
                preg_match_all('/\[(.*?)\]/', $post['activity_payment_id'], $matches1);
                $post['activity_payment_id'] = $matches1[1][0];
                // 支付账户
                preg_match_all('/\[(.*?)\]/', $post['recom_payment_id'], $matches2);
                $post['recom_payment_id'] = $matches2[1][0];
                // 盲盒活动
                if (!empty($post['platform_box_id'])) {
                    preg_match_all('/\[(.*?)\]/', $post['platform_box_id'], $matches3);
                    $post['platform_box_id'] = $matches3[1][0];
                }
                // 勾选所填信息
                $post['draw_prize_fill_info'] = json_encode($post['draw_prize_fill_info']);
                // 保存数据
                $save = $this->model->save($post);
                // 新增自定义数据
                $data1 = [
                    // 倒计时背景颜色
                    ['activity_id' => $this->model->id, 'custom_code' => 'countdown_bgcolor', 'custom_value' => $post['countdown_bgcolor']],
                    // 按钮[我的]自定义名称、颜色
                    ['activity_id' => $this->model->id, 'custom_code' => 'my_botton_name', 'custom_value' => $post['my_botton_name']],
                    ['activity_id' => $this->model->id, 'custom_code' => 'my_botton_color', 'custom_value' => $post['my_botton_color']],
                    // 按钮[立即购买]自定义名称、颜色
                    ['activity_id' => $this->model->id, 'custom_code' => 'buy_botton_name', 'custom_value' => $post['buy_botton_name']],
                    ['activity_id' => $this->model->id, 'custom_code' => 'buy_botton_color', 'custom_value' => $post['buy_botton_color']],
                    // 按钮[立即分享]自定义名称、颜色
                    ['activity_id' => $this->model->id, 'custom_code' => 'share_botton_name', 'custom_value' => $post['share_botton_name']],
                    ['activity_id' => $this->model->id, 'custom_code' => 'share_botton_color', 'custom_value' => $post['share_botton_color']],
                ];
                foreach ($data1 as $v) {
                    Db::name('activity_custom')->insert(array_merge($v, ['create_time' => date('Y-m-d H:i:s'), 'update_time' => date('Y-m-d H:i:s')]));
                }
            } catch (\Exception $e) {
                return $this->error('保存失败:' . $e->getMessage());
            }
            return $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnnotation(title="编辑")
     */
    public function edit(Request $request)
    {
        $id  = (int)$request->input('id');
        $row = $this->model->find($id);
        // 勾选所填信息
        $row['draw_prize_fill_info'] = json_decode($row['draw_prize_fill_info'], true);
        // 收款账户
        $row['activity_payment_id'] = '['.$row['activity_payment_id'].'] '.Db::name('payment_account')->where(['id' => $row['activity_payment_id']])->value('name');
        // 支付账户
        $row['recom_payment_id'] = '['.$row['recom_payment_id'].'] '.Db::name('payment_account')->where(['id' => $row['recom_payment_id']])->value('name');
        // 盲盒活动
        if (!empty($row['platform_box_id'])) {
            $row['platform_box_id'] = '['.$row['platform_box_id'].'] '.Db::name('platform_box')->where(['id' => $row['platform_box_id']])->value('name');
        } else {
            $row['platform_box_id'] = '';
        }
        // 获取自定义数据
        $row['custom'] = Db::name('activity_custom')->where(['activity_id' => $row['id']])->column('custom_value', 'custom_code');
        if (empty($row)) return $this->error('数据不存在');
        if ($request->isAjax()) {
            $post = $request->post();
            try {
                // 收款账户
                preg_match_all('/\[(.*?)\]/', $post['activity_payment_id'], $matches1);
                $post['activity_payment_id'] = $matches1[1][0];
                // 支付账户
                preg_match_all('/\[(.*?)\]/', $post['recom_payment_id'], $matches2);
                $post['recom_payment_id'] = $matches2[1][0];
                // 盲盒活动
                if (!empty($post['platform_box_id'])) {
                    preg_match_all('/\[(.*?)\]/', $post['platform_box_id'], $matches3);
                    $post['platform_box_id'] = $matches3[1][0];
                }
                // 勾选所填信息
                $post['draw_prize_fill_info'] = json_encode($post['draw_prize_fill_info']);
                // 保存数据
                $save = $row->save($post);
                // 保存自定义数据
                $data = [
                    // 倒计时背景颜色
                    ['activity_id' => $row['id'], 'custom_code' => 'countdown_bgcolor', 'custom_value' => $post['countdown_bgcolor']],
                    // 按钮[我的]自定义名称、颜色
                    ['activity_id' => $row['id'], 'custom_code' => 'my_botton_name', 'custom_value' => $post['my_botton_name']],
                    ['activity_id' => $row['id'], 'custom_code' => 'my_botton_color', 'custom_value' => $post['my_botton_color']],
                    // 按钮[立即购买]自定义名称、颜色
                    ['activity_id' => $row['id'], 'custom_code' => 'buy_botton_name', 'custom_value' => $post['buy_botton_name']],
                    ['activity_id' => $row['id'], 'custom_code' => 'buy_botton_color', 'custom_value' => $post['buy_botton_color']],
                    // 按钮[立即分享]自定义名称、颜色
                    ['activity_id' => $row['id'], 'custom_code' => 'share_botton_name', 'custom_value' => $post['share_botton_name']],
                    ['activity_id' => $row['id'], 'custom_code' => 'share_botton_color', 'custom_value' => $post['share_botton_color']],
                ];
                foreach ($data as $v) {
                    $find = Db::name('activity_custom')->where(['activity_id' => $row['activity_id'], 'custom_code' => $v['custom_code']])->find();
                    if (empty($find)) {
                        Db::name('activity_custom')->insert(array_merge($v, ['create_time' => date('Y-m-d H:i:s'), 'update_time' => date('Y-m-d H:i:s')]));
                    } else {
                        Db::name('activity_custom')->update(array_merge($v, ['id' => $find['id'], 'update_time' => date('Y-m-d H:i:s')]));
                    }
                }
            } catch (\PDOException|\Exception $e) {
                return $this->error('保存失败:' . $e->getMessage());
            }
            return $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign(compact('row'));
        return $this->fetch();
    }

    /**
     * @NodeAnnotation(title="删除")
     */
    public function delete(Request $request): Response
    {
        if (!$request->isAjax()) return $this->error();
        $id = $request->input('id');
        if (!is_array($id)) $id = (array)$id;
        $row = $this->model->whereIn('id', $id)->field('id')->select()->toArray();
        if (empty($row)) return $this->error('数据不存在');
        try {
            $save = $this->model->whereIn('id', $id)->delete();
        } catch (\PDOException|\Exception $e) {
            return $this->error('删除失败:' . $e->getMessage());
        }
        return $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * @NodeAnnotation(title="解除绑定")
     */
    public function removeBinding(Request $request): Response
    {
        $id  = (int)$request->input('id');
        $row = $this->model->find($id);

        try {
            $this->model->whereIn('id', $id)->update(['user_id' => null]);
            Db::name('activity_user_role')->where(['activity_id' => $row['id'], 'role' => 1])->update(['role' => 0]);
            return $this->success('解除成功');
        } catch (\Exception $e) {
            return $this->error('解除失败');
        }
    }

    /**
     * @NodeAnnotation(title="导出")
     */
    public function export(Request $request): Response|bool
    {
        try {
            // 兼容其他搜索模式
            $id = $request->get('id', '');
            if (!empty($id)) {
                $where[] = ['id', '=', $id];
            } else {
                list($page, $limit, $where) = $this->buildTableParams();
            }
            $list = $this->model->where($where)->order($this->order)->select()->toArray();
            foreach ($list as $key => $value) {
                // 勾选所填信息
                $draw_prize_fill_info = '';
                foreach (json_decode($value['draw_prize_fill_info'] ?? '[]', true) as $v) {
                    switch ($v) {
                        case '1':
                            $draw_prize_fill_info .= '姓名、';
                            break;
                        case '2':
                            $draw_prize_fill_info .= '电话、';
                            break;
                        case '3':
                            $draw_prize_fill_info .= '地址、';
                            break;
                    }
                }
                // 收款账户
                $value['activity_payment_id'] = empty($value['activity_payment_id']) ? '' : '['.$value['activity_payment_id'].'] '.Db::name('payment_account')->where(['id' => $value['activity_payment_id']])->value('name');
                // 支付账户
                $value['recom_payment_id'] = empty($value['recom_payment_id']) ? '' : '['.$value['recom_payment_id'].'] '.Db::name('payment_account')->where(['id' => $value['recom_payment_id']])->value('name');
                // 盲盒活动
                $value['platform_box_id'] = empty($value['platform_box_id']) ? '' : '['.$value['platform_box_id'].'] '.Db::name('platform_box')->where(['id' => $value['platform_box_id']])->value('name');
                // 获取自定义数据
                $custom = Db::name('activity_custom')->where(['activity_id' => $value['id']])->column('custom_value', 'custom_code');
                $data[$key] = [
                    $value['id'], (($value['status'] == 1) ? '上架' : '下架'), $value['activity_title'], $value['activity_head_image'], $value['activity_original_price'], $value['activity_present_price'], $value['activity_stock'],
                    $value['activity_quota'], $value['activity_start_time'], $value['activity_end_time'], $value['activity_detail_image'], $value['activity_payment_id'], $value['activity_virtual_sales'], $value['activity_virtual_visitor'],
                    $value['activity_virtual_join'], $value['activity_virtual_share'], (($value['recom_is_buy'] == 1) ? '是' : '否'), $value['recom_reward_amount'], (($value['recom_payment_prize_plus_one'] == 1) ? '是' : '否'),
                    $value['recom_payment_id'], $value['share_title'], $value['share_describe'], $value['share_image'], $value['poster_image'], $value['seller_name'], $value['seller_address'], $value['seller_phone'], $value['seller_shop_image'],
                    $value['draw_prize_number'], $draw_prize_fill_info, (($value['draw_prize_is_payment'] == 1) ? '支付后领奖' : '直接领奖'), $value['draw_prize_tip'], (($value['platform_box_is_join'] == 1) ? '是' : '否'), $value['platform_box_id'],
                    $custom['countdown_bgcolor'] ?? '', $custom['my_botton_name'] ?? '', $custom['my_botton_color'] ?? '', $custom['buy_botton_name'] ?? '', $custom['buy_botton_color'] ?? '', $custom['share_botton_name'] ?? '', $custom['share_botton_color'] ?? ''
                ];
            }
            $spreadsheet = excel::handleExcel([[
                'name' => '活动列表',
                'title' => [
                    'ID', '活动状态', '活动名称', '首图', '原价', '现价', '库存数量', '限购数量', '活动开始时间', '活动结束时间', '活动详情图片', '收款账户', '虚拟销量', '虚拟浏览量', '虚拟参与人数', '虚拟分享数',
                    '是否需要购买', '奖励金额', '支付后是否增加一次抽奖', '支付账户', '分享标题', '分享描述', '分享图片', '海报图片', '商家名称', '商家地址', '商家电话', '门店照片', '每人抽奖次数', '勾选所填信息',
                    '是否支付后领奖', ' 领取说明', '是否参与平台盲盒', '盲盒活动', '倒计时背景颜色', '[我的]名称', '[我的]颜色', '[立即购买]名称', '[立即购买]颜色', '[立即分享]名称', '[立即分享]颜色'
                ],
                'data' => $data
            ]], []);
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');

            $file_name = '导出活动列表';
            $file_path = runtime_path() . '/excel/' . $file_name . time() . '.' . mt_rand(100000, 999999) . '.xlsx';
            // 保存文件到 public 下
            $writer->save($file_path);
            // 下载文件
            return response()->download($file_path, $file_name . '.xlsx');
        } catch (\Exception|\PhpOffice\PhpSpreadsheet\Exception$e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * @NodeAnnotation(title="属性修改")
     */
    public function modify(Request $request): Response
    {
        if (!$request->isAjax()) return $this->error();
        $post = $request->post();
        $rule = [
            'id|ID'      => 'require',
            'field|字段' => 'require',
        ];
        try {
            $this->validate($post, $rule);
        } catch (Exception $exception) {
            return $this->error($exception->getMessage());
        }
        $row = $this->model->find($post['id']);
        if (empty($row)) {
            return $this->error('数据不存在');
        }
        try {
            foreach ($post as $key => $item) {
                // 平台盲盒参加状态判定
                if ($item == 'platform_box_is_join') {
                    $platform_box_id = Db::name('activity')->where(['id' => $post['id']])->value('platform_box_id');
                    if (empty($platform_box_id) && $post['value'] == 1) {
                        return $this->error("未设置平台盲盒活动，操作失败！");
                    }
                    $platform_box_data = Db::name('platform_box')->where(['id' => $platform_box_id])->find();
                    if (empty($platform_box_data) && $post['value'] == 1) {
                        return $this->error("平台盲盒活动失效，操作失败！");
                    }
                }
                if ($key == 'field') $row->$item = $post['value'];
            }
            $row->save();
        } catch (\PDOException|\Exception $e) {
            return $this->error("操作失败:" . $e->getMessage());
        }
        return $this->success('保存成功');
    }

    /**
     * @NodeAnnotation(title="生成微信小程序二维码")
     */
    public function wxappQrcode(Request $request) : Response
    {
        // 生成小程序二维码
        $miniapp_appid = sysconfig('wechat','miniapp_appid');
        $miniapp_appsecret = sysconfig('wechat','miniapp_appsecret');

        $wxqrcode = (new \app\extend\WxUtil\WxTool)->wxappQrcode($miniapp_appid, $miniapp_appsecret, [
            'page' => $request->get('page', 'pages/index/index'),
            'scene' => $request->get('scene', 'index'),
            'width' => $request->get('width', '430')
        ]);
        if ($wxqrcode['code'] == 0) {
            // 发送图像
            return response(base64_decode($wxqrcode['data']))->header('Content-Type', 'image/png');
        } else {
            return $this->error($wxqrcode['msg']);
        }
    }

}
